<?php

namespace app\controllers\admin\uni\bao;

use app\controllers\admin\base\AdminController;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\UserBao as Model;

class BaoController extends AdminController
{
    public function actionList()
    {
        $user_id = $this->post('user_id');
        $send_id = $this->post('send_id');
        $export = $this->post('export');

        $start = $this->post('start');
        $end = $this->post('end');

        $page = intval($this->post('page', $this->page));
        $page_size = intval($this->post('pageSize', $this->pageSize));

        $sort = $this->post('sort');
        $status = $this->post('status', -1);

        $query = Model::find()
            ->where(['is_platform' => 1]);

        if ($status != -1) {
            $query->andWhere(['final' => $status]);
        }

        if ($sort) {
            $prop = substr($sort, 0, 1);
            $prop = $prop == '-' ? SORT_DESC : SORT_ASC;
            $order = substr($sort, 1);
            $query->orderBy([$order => $prop]);
        } else {
            $query->orderBy(['id' => SORT_DESC]);
        }

        if ($send_id) {
            $query->andWhere(['send_id' => $send_id]);
        }
        if ($user_id) {
            $query->andWhere(['user_id' => $user_id]);
        }

        if ($start) {
            $query->andWhere(['>=', 'create_time', $start]);
        }
        if ($end) {
            $query->andWhere(['<=', 'create_time', $end]);
        }

        // export
        if ($export) {
            $list = $query->asArray()->all();
            foreach ($list as &$item) {
                if ($item['log']) {
                    $item['log'] = json_decode($item['log'], true);
                }
            }
            return $this->success($list);
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->asArray()
            ->all();

        foreach ($list as &$item) {
            if ($item['log']) {
                $item['log'] = json_decode($item['log'], true);
            }
        }

        if ($user_id) {
            $quantity = Model::find()
                ->where(['is_platform' => 1])
                ->andWhere(['user_id' => $user_id])
                ->andWhere(['status' => 1]);
            if ($start) {
                $quantity->andWhere(['>=', 'create_time', $start]);
            }
            if ($end) {
                $quantity->andWhere(['<=', 'create_time', $end]);
            }
            $quantity = (int)$quantity->sum('quantity');

            $score = Model::find()
                ->where(['is_platform' => 1])
                ->andWhere(['user_id' => $user_id])
                ->andWhere(['status' => 1]);
            if ($start) {
                $score->andWhere(['>=', 'create_time', $start]);
            }
            if ($end) {
                $score->andWhere(['<=', 'create_time', $end]);
            }
            $score = (float)$score->sum('score');

            $count = Model::find()
                ->where(['is_platform' => 1])
                ->andWhere(['user_id' => $user_id])
                ->andWhere(['status' => 1]);
            if ($start) {
                $count->andWhere(['>=', 'create_time', $start]);
            }
            if ($end) {
                $count->andWhere(['<=', 'create_time', $end]);
            }
            $count = (int)$count->count();

            $data = [
                'quantity' => $quantity,
                'score' => $score,
                'count' => $count,
            ];


        } else {
            $data = [];
        }

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
            'data' => $data,
        ]);

    }

    public function actionCheck()
    {

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $id = $this->post('id');
            $model = Model::findOne(['id' => $id]);

            if ($model->final == 1) {
                // throw new \Exception('已经处理过了');
            }

            $model->status = 1;
            $model->final = 1;
            $model->save();

            if ($model->final_id > 0) {
                Model::updateAll(['status' => 1, 'final' => 1], [
                    'or',
                    ['id' => $model->final_id],
                    ['final_id' => $model->final_id]
                ]);
            }

            // 给最终用户加上积分
            $account = UserAccount::findOne(['user_id' => $model->user_id]);
            if ($account->tmp_score >= $model->score) {
                $account->score += $model->score;
                $account->tmp_score -= $model->score;
                $account->save();

                $commission = new UserCommission();
                $commission->user_id = $account->user_id;
                $commission->score = $model->score;
                $commission->award_name = '报单';
                $commission->award_type = '100';
                $commission->status = 1;
                $commission->save();

                // 日志
                $log = [
                  'name' => $this->user->username,
                  'time' => date('Y-m-d H:i:s'),
                  'text' => '审核了此订单'
                ];
                $model->log = json_encode($log);
                $model->save();
            }
            $transaction->commit();
            return $this->success();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail();
        }
    }

    // 批量审核
    public function actionCheckBatch()
    {
        $ids = $this->post('ids');

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $list = Model::find()
                ->where(['id' => $ids])
                ->all();

            foreach ($list as $model) {
                if ($model->final == 1) {
                    throw new \Exception('存在已经审核过的订单');
                }
                if ($model->final == -99) {
                    throw new \Exception('存在删除过的订单');
                }
                $this->_batch($model);
            }

            $transaction->commit();
            return $this->success();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage());
        }
    }

    private function _batch($model)
    {
        $model->status = 1;
        $model->final = 1;
        $model->save();

        if ($model->final_id > 0) {
            Model::updateAll(['status' => 1, 'final' => 1], [
                'or',
                ['id' => $model->final_id],
                ['final_id' => $model->final_id]
            ]);
        }

        // 给最终用户加上积分
        $account = UserAccount::findOne(['user_id' => $model->user_id]);
        if ($account->tmp_score >= $model->score) {
            $account->score += $model->score;
            $account->tmp_score -= $model->score;
            $account->save();

            $commission = new UserCommission();
            $commission->user_id = $account->user_id;
            $commission->score = $model->score;
            $commission->award_name = '报单';
            $commission->award_type = '100';
            $commission->status = 1;
            $commission->save();
        }

        // 日志
        $log = [
            'name' => $this->user->username,
            'time' => date('Y-m-d H:i:s'),
            'text' => '审核了此订单'
        ];
        $model->log = json_encode($log);
        $model->save();
    }

    // 删除
    public function actionDelete()
    {
        // return $this->fail('测试中');

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $id = $this->post('id');
            $model = Model::findOne(['id' => $id]);

            // var_dump($id);exit;

            if ($model->final != 0) {
                throw new \Exception('已经处理过了');
            }

            $model->status = -99;
            $model->final = -99;
            $model->save();

            // 删除链条上的
            if ($model->final_id > 0) {
                Model::updateAll(['status' => -99, 'final' => -99], [
                    'or',
                    ['id' => $model->final_id],
                    ['final_id' => $model->final_id]
                ]);
            }

            // 日志
            $log = [
                'name' => $this->user->username,
                'time' => date('Y-m-d H:i:s'),
                'text' => '删除了该订单'
            ];
            $model->log = json_encode($log);
            $model->save();

            $transaction->commit();
            return $this->success();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage());
        }
    }

    // 修复已审核BUG, 因为final_id = 0 出现
    // SELECT b.*, c.score as cc, c.create_time as t FROM `user_commission` as c, user_bao as b
    // where b.final = 1 and c.user_id = b.user_id and b.update_time = c.create_time
    public function actionHas()
    {
        $id = $this->post('id');

        $model = \Yii::$app->db->createCommand(
            'SELECT b.*, c.score as cc, c.create_time as t 
                FROM user_commission as c, user_bao as b 
                where b.id = :id 
                and b.final = 1 and c.user_id = b.user_id and b.update_time = c.create_time')
            ->bindValues([':id' => $id])
            ->queryOne();

        // var_dump($model);exit;

        if ($model) {
            return $this->success([
                'score' => $model['cc'],
                'time' => $model['t'],
            ]);
        }

        // 这个才是重要的
        return $this->fail('该订单未被审核过!!!');

    }

    // 设为未审核
    public function actionSet()
    {
        $id = $this->post('id');
        $model = Model::findOne(['id' => $id]);


        $has = \Yii::$app->db->createCommand(
            'SELECT b.*, c.score as cc, c.create_time as t 
                FROM user_commission as c, user_bao as b 
                where b.id = :id 
                and b.final = 1 and c.user_id = b.user_id and b.update_time = c.create_time')
            ->bindValues([':id' => $id])
            ->queryOne();

        if ($has) {
            return $this->fail('已经被审核过,不能更改了!');
        }

        if ($model) {
            $model->status = 0;
            $model->final = 0;
            $model->save();

            return $this->success();
        }
    }
}